package com.yxh.activity;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yxh.R;
import com.yxh.dto.LessonDto;
import com.yxh.dto.UserDto;
import com.yxh.fragment.ClassFragment;
import com.yxh.fragment.HomeFragment;
import com.yxh.service.Task;
import com.yxh.util.DateUtil;
import com.yxh.util.Options;
import com.yxh.view.CommonDialog;
import com.yxh.view.TimePickerDialog;

@SuppressLint("InflateParams")
public class ClassTimeSettingActivity extends BaseActivity implements
		OnClickListener {

	private TextView layout1Tv1, layout1Tv2;

	private LinearLayout pLayout;

	private List<TextView> dataTvList;

	/**
	 * 0 homeFragment 1:classSelectActivity 2:ClassFragment
	 * 3:aboutMeClassActivity
	 **/

	private String resource;

	private LessonDto dto;

	private Animation animation;

	private DisplayImageOptions options;

	private ImageLoader imageLoader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_time_setting);

		initView();

		initData();

		overridePendingTransition(R.anim.enter_righttoleft, R.anim.noanim);
	}

	public void initView() {
		Intent it = getIntent();
		resource = it.getStringExtra("resource");
		dto = (LessonDto) it.getSerializableExtra("dto");

		/*** top view ***/
		((TextView) findViewById(R.id.head_layout_tv))
				.setText(R.string.activity_main_settings_time);
		// LogUtil.e("dto -->" + dto);
		if (dto == null) {
			return;
		}
		animation = AnimationUtils.loadAnimation(mContext, R.anim.shake);

		layout1Tv1 = (TextView) findViewById(R.id.layout1_tv1);
		layout1Tv2 = (TextView) findViewById(R.id.layout1_tv2);
		layout1Tv1.setText(dto.name);
		layout1Tv2.setText(dto.intro);

		imageLoader = ImageLoader.getInstance();
		if (!imageLoader.isInited()) {
			Options.initImageLoaderConfiguration(ImageLoader.getInstance(),
					mContext);
		}
		options = Options.getListOptions2();
		if (!TextUtils.isEmpty(dto.url)) {
			imageLoader.displayImage(dto.url,
					(ImageView) findViewById(R.id.layout1_img1), options);
		}

		/*** item view ***/
		dataTvList = new ArrayList<TextView>();
		pLayout = (LinearLayout) findViewById(R.id.pLayout);
		for (int i = 0; i < dto.dateList.size(); i++) {
			final int pos = i;
			View view = LayoutInflater.from(mContext).inflate(
					R.layout.activity_time_setting_item, null);
			((TextView) view.findViewById(R.id.setting_time_tv1))
					.setText(dto.dateList.get(i).nodeName);
			dataTvList.add((TextView) view.findViewById(R.id.setting_time_tv2));

			if (!TextUtils.isEmpty(dto.dateList.get(i).nodeDate))
				dataTvList.get(i).setText(
						DateUtil.TimeStamp3Date(dto.dateList.get(i).nodeDate));

			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					showDateDialog(dto.dateList.get(pos).nodeName, pos);
				}

			});
			pLayout.addView(view);
		}

		findViewById(R.id.btn).setOnClickListener(this);
	}

	private void initData() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.btn:
			goSetClassTime();
			break;

		}
	}

	private void goSetClassTime() {

		if (!checkDataValue()) {
			return;
		}

		showsetDefaultClassDialog();

	}

	private void showsetDefaultClassDialog() {
		CommonDialog dialog = new CommonDialog(this, CommonDialog.NOTITLE);
		dialog.setTitle("您是否要切换进入当前课程");
		dialog.setOkContent("是");
		dialog.setCancleContent("否");
		// dialog.setCancelable(false);
		dialog.setOkOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
				setClassTime(1); // 设为默认课程
			}
		});
		dialog.setCancleOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
				setClassTime(0);// 设为默认课程
			}

		});
		dialog.show();
	}

	/**
	 * 提交设置时间
	 * lesson_id（课程id）、node_dates（节点时间戳，按先后顺序排列，逗号隔开，必填）、default（是否为默认课程，1
	 * 或0，必填）、device_code（设备码，必填）、token（令牌，必填）
	 * **/
	private void setClassTime(int isDefault) {
		String nodeDatas = "";
		for (int i = 0; i < dataTvList.size(); i++) {
			String c = dataTvList.get(i).getText().toString();
			String d = "";
			if (!TextUtils.isEmpty(c))
				d = DateUtil.date2TiemStamp(c);
			if (i != 0) {
				nodeDatas += ",";
			}
			nodeDatas += d;
		}

		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/set_node");
		map.put("lesson_id", dto.lessonId);
		map.put("node_dates", nodeDatas);
		map.put("default", String.valueOf(isDefault));
		getData(map, Task.SET_CLASS_NODE, 1);

	}

	@Override
	public void refresh(Object... param) {
		try {
			int operType = (Integer) param[0];
			Object obj = param[1];
			closeDialog();
			switch (operType) {
			case Task.SET_CLASS_NODE:
				if (obj != null) {
					UserDto dto = (UserDto) obj;
					if ("1".equals(dto.result)) {
						// 0 homeFragment 1:classSelectActivity
						// 2:ClassFragment 3:AboutClassactivity
						if ("0".equals(resource)) {//
							Intent it1 = new Intent(HomeFragment.REFRUSH_HOME);
							sendBroadcast(it1);
						} else if ("1".equals(resource)) {//
							Intent it1 = new Intent(HomeFragment.REFRUSH_HOME);
							sendBroadcast(it1);
						} else if ("2".equals(resource)) {//
							Intent it1 = new Intent(
									ClassFragment.COM_REFRUSH_CLASS);
							sendBroadcast(it1);
							Intent it2 = new Intent(HomeFragment.REFRUSH_HOME);
							sendBroadcast(it2);
						} else if ("3".equals(resource)) {
							Intent it1 = new Intent(
									AboutMeClassActivity.COM_REFRUSH_CLASS);
							sendBroadcast(it1);

							Intent it2 = new Intent(
									ClassFragment.COM_REFRUSH_CLASS);
							sendBroadcast(it2);

							Intent it3 = new Intent(HomeFragment.REFRUSH_HOME);
							sendBroadcast(it3);
						}
						finish();
					} else
						showToast(dto.message);
				} else {
					showToast("网络连接异常,请检查网络");
				}
				break;

			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showDateDialog(String title, final int pos) {
		TimePickerDialog dialog = new TimePickerDialog(this);
		dialog.setDatePickerTitle(title);
		dialog.setInitDataPickerTime(DateUtil.date2TiemStamp(dataTvList
				.get(pos).getText().toString()));
		dialog.setOkOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				TimePickerDialog dialog = (TimePickerDialog) v.getTag();
				dialog.dismiss();
				dataTvList.get(pos).setText(dialog.getSelectedDate());
				setDateValue();

			}
		});

		dialog.setCancleOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				TimePickerDialog dialog = (TimePickerDialog) v.getTag();
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	private void setDateValue() {
		if (dataTvList == null || dataTvList.size() < 2) {
			return;
		}
		for (int i = 1; i < dataTvList.size(); i++) {
			String c1 = dataTvList.get(i - 1).getText().toString();
			long d1 = 0;
			if (!TextUtils.isEmpty(c1))
				d1 = DateUtil.date2TiemStamp2(c1);

			String c2 = dataTvList.get(i).getText().toString();
			long d2 = 0;
			if (!TextUtils.isEmpty(c2))
				d2 = DateUtil.date2TiemStamp2(c2);

			if (d2 - d1 < 0) {
				dataTvList.get(i).setTextColor(Color.RED);
			} else {
				dataTvList.get(i).setTextColor(Color.parseColor("#999999"));
			}
		}
	}

	private boolean checkDataValue() {
		if (dataTvList == null || dataTvList.size() < 2) {
			return true;
		}

		for (int i = 1; i < dataTvList.size(); i++) {
			String c1 = dataTvList.get(i - 1).getText().toString();
			long d1 = 0;
			if (!TextUtils.isEmpty(c1))
				d1 = DateUtil.date2TiemStamp2(c1);

			String c2 = dataTvList.get(i).getText().toString();
			long d2 = 0;
			if (!TextUtils.isEmpty(c2))
				d2 = DateUtil.date2TiemStamp2(c2);

			if (d2 - d1 < 0) {
				showToast("每个时间节点不能晚于上个节点");
				dataTvList.get(i).setFocusable(true);
				dataTvList.get(i).requestFocus();
				dataTvList.get(i).startAnimation(animation);
				return false;
			}
		}
		return true;
	}

}